package com.itheima.Interceptor;

import com.itheima.util.JwtUtils;
import com.itheima.pojo.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(true) {
            CurrentHolder.setUserId(2);
            return true;
        }
        //1. 获取请求url
        String url = request.getRequestURL().toString();
        log.info("拦截到请求: {}", url);

        //2. 判断是否为登录请求，如果是则直接放行
        if (url.contains("/login")) {
            log.info("登录请求，直接放行");
            return true;
        }

        //3. 获取请求头中的令牌（token）
        String token = request.getHeader("token");

        //4. 判断token是否存在
        if (!StringUtils.hasText(token)) {
            log.info("请求头中缺少token，返回未授权");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(Result.error("用户未登录")));
            return false;
        }

        //5. 解析token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = (Integer) claims.get("userId");
            CurrentHolder.setUserId(userId); // 设置当前用户ID
            log.info("token解析成功，用户已认证，用户ID: {}", userId);
        } catch (Exception e) {
            log.warn("token解析失败: {}", e.getMessage());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(Result.error("用户认证失败")));
            return false;
        }

        //6. 放行
        log.info("用户认证成功，放行请求");
        return true;
    }
}